package com.example.controller;

import com.example.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Date 2020/6/21 23:39
 * @Author jacklin
 */

@RestController
@RequestMapping(value = "/redis")
public class RedisTestController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/putIntoSession")
    public UserEntity putIntoSession(HttpServletRequest request) {
        UserEntity user = new UserEntity();
        user.setUsername("jacklin");
        user.setPassword("123456");
        request.getSession().setAttribute("current_user", user);
        return user;
    }

    @RequestMapping("/getFromSession")
    public boolean getFromSession(HttpServletRequest request) {
        UserEntity user = (UserEntity) request.getSession().getAttribute("current_user");
        return "jacklin".equals(user.getUsername()) ? true : false;
    }

    @RequestMapping("/putIntoRedis")
    public UserEntity putIntoRedis(HttpServletRequest request) {
        UserEntity user = new UserEntity();
        user.setUsername("jacklin");
        user.setPassword("123456");
        redisTemplate.opsForValue().set("current_user", user);
        return user;
    }

    @RequestMapping("/getFromRedis")
    public boolean getFromRedis(HttpServletRequest request) {
        UserEntity user = (UserEntity) redisTemplate.opsForValue().get("current_user");
        return "jacklin".equals(user.getUsername()) ? true : false;
    }
}
